import psutil
import datetime


def get_key():
    key_info = psutil.net_io_counters(pernic=True).keys()  # 获取网卡名称

    recv = {}
    sent = {}

    for key in key_info:
        recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv)  # 各网卡接收的字节数
        sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent)  # 各网卡发送的字节数

    return key_info, recv, sent


def get_rate(func):
    """获取网络流量数据"""
    import time

    key_info, old_recv, old_sent = func()  # 上一秒收集的数据

    time.sleep(1)

    key_info, now_recv, now_sent = func()  # 当前所收集的数据

    net_in = {}
    net_out = {}

    for key in key_info:
        net_in.setdefault(key, now_recv.get(key) - old_recv.get(key))  # 每秒接收速率
        net_out.setdefault(key, now_sent.get(key) - old_sent.get(key))  # 每秒发送速率

    return key_info, net_in, net_out


def computer_info():
    """ 获取机器信息"""
    # cpu核数
    cpu_count = psutil.cpu_count()
    # 当前cpu利用率:
    cpu_lv = psutil.cpu_percent(1)
    memory = psutil.virtual_memory()
    # 当前内存使用率
    memory_lv = float(memory.used) / float(memory.total) * 100

    # 开机时间
    boot_time = psutil.boot_time()
    # 硬盘信息
    disk_partitions = psutil.disk_partitions()
    disk_list = []
    for disk in disk_partitions:
        disk_usage = psutil.disk_usage(disk.device)
        disk_list.append(
            {"device": disk.device[0],
             "total": disk_usage.total,
             "percent": disk_usage.percent,
             "free": disk_usage.free,
             "used": disk_usage.used}
        )

    # 网卡信息
    key_info, net_in, net_out = get_rate(get_key)
    net_info = {}
    input_rate = 0
    output_rate = 0
    for key in key_info:
        input_rate += net_in.get(key)
        output_rate += net_out.get(key)
        net_info.setdefault(key, {"in": net_in.get(key), "out": net_out.get(key)})
    net_info.setdefault("input_rate", input_rate)
    net_info.setdefault("output_rate", output_rate)
    return {"cpu_percent": cpu_lv,
            "memory_percent": memory_lv,
            "cpu_count": cpu_count,
            "memory_free": memory.free,
            "memory_used": memory.used,
            "memory_total": memory.total,
            "boot_time": datetime.datetime.fromtimestamp(boot_time).strftime(
                "%Y-%m-%d %H:%M:%S"),
            "disk_list": disk_list,
            "net_info": net_info,
            "process_list": get_process_list()}


def get_process_list():
    """获取正在运行的程序"""
    process_list = []
    pl = psutil.pids()
    for pid in pl:
        try:
            process_list.append(psutil.Process(pid).name())
        except psutil.NoSuchProcess:
            pass
    return process_list


def judge_process(process_name):
    """判断程序是否正在运行"""
    return process_name in get_process_list()

